<?php
/**
	 * @author Nguyen Xuan Hong
	 * @copyright 2010
	 */
						
# Function detail : Convert VietNamese - String to ASCII-String
# @param <string>
function ascii_convert($str) {
	$chars = array(
		'a'	=>	array('ấ','ầ','ẩ','ẫ','ậ','Ấ','Ầ','Ẩ','Ẫ','Ậ','ắ','ằ','ẳ','ẵ','ặ','Ắ','Ằ','Ẳ','Ẵ','Ặ','á','à','ả','ã','ạ','â','ă','Á','À','Ả','Ã','Ạ','Â','Ă'),
		'e' =>	array('ế','ề','ể','ễ','ệ','Ế','Ề','Ể','Ễ','Ệ','é','è','ẻ','ẽ','ẹ','ê','É','È','Ẻ','Ẽ','Ẹ','Ê'),
		'i'	=>	array('í','ì','ỉ','ĩ','ị','Í','Ì','Ỉ','Ĩ','Ị'),
		'o'	=>	array('ố','ồ','ổ','ỗ','ộ','Ố','Ồ','Ổ','Ô','Ộ','ớ','ờ','ở','ỡ','ợ','Ớ','Ờ','Ở','Ỡ','Ợ','ó','ò','ỏ','õ','ọ','ô','ơ','Ó','Ò','Ỏ','Õ','Ọ','Ô','Ơ'),
		'u'	=>	array('ứ','ừ','ử','ữ','ự','Ứ','Ừ','Ử','Ữ','Ự','ú','ù','ủ','ũ','ụ','ư','Ú','Ù','Ủ','Ũ','Ụ','Ư'),
		'y'	=>	array('ý','ỳ','ỷ','ỹ','ỵ','Ý','Ỳ','Ỷ','Ỹ','Ỵ'),
		'd'	=>	array('đ','Đ')
	);
	foreach ($chars as $key => $arr) 
		foreach ($arr as $val)
			$str = str_replace($val,$key,$str);
	return $str;
}	

# Function detail : Convert VietNamese - String to ASCII-String for title ajax type
# @param <string>
function ascii_convert_ex($str){
	$str = convert_ascii($str);
	$str = str_replace(' ','-',$str);
	return $str;
}

# Function detail : Convert special char to html char
# @param <string>
function htmlchars($str) {
	return str_replace(
		array('&', '<', '>', '"', chr(92), chr(39)),
		array('&amp;', '&lt;', '&gt;', '&quot;', '&#92;', '&#39'),
		$str
	);
}

# Function detail : UbConvert special char to html char
# @param <string>
function unhtmlchars($str) {
	return str_replace(array('&lt;', '&gt;', '&quot;', '&amp;', '&#92;', '&#39'), array('<', '>', '"', '&', chr(92), chr(39)), $str);
}

# ArrayObject name : Yahoo replace emoticons
# @param <string>
function arr_yahoo_emoticons() {
	return array(
			6 => '>:D<',		18 => '#:-S',				36 => '<:-P',		42 => ':-SS',
			48 => '<):)',		50 => '3:-O',				51 => ':(|)',		53 => '@};-',
			55 => '**==',		56 => '(~~)',				58 => '*-:)',		63 => '[-O<',
			67 => ':)>-',		77 => '^:)^',				106 => ':-??',		25 => 'O:)',
			26 => ':-B',		28 => 'I-)',				29 => '8-|',		30 => 'L-)',
			31 => ':-&',		32 => ':-$',				33 => '[-(',		34 => ':O)',
			35 => '8-}',		7 => ':-/',					37 => '(:|',		38 => '=P~',
			39 => ':-?',		40 => '#-O',				41 => '=D>',		9 => ':">',
			43 => '@-)',		44 => ':^O',				45 => ':-W',		46 => ':-<',
			47 => '>:P',		11 => array(':*',':-*'),	49 => ':@)',		12 => '=((',
			13 => ':-O',		52 => '~:>',				16 => 'B-)',		54 => '%%-',
			17 => ':-S',		5 => ';;)',					57 => '~O)',		19 => '>:)',
			59 => '8-X',		60 => '=:)',				61 => '>-)',		62 => ':-L',
			20 => ':((',		64 => '$-)',				65 => ':-"',		66 => 'B-(',
			21 => ':))',		68 => '[-X',				69 => '\:D/',		70 => '>:/',
			71 => ';))',		72 => 'O->',				73 => 'O=>',		74 => 'O-+',
			75 => '(%)',		76 => ':-@',				23 => '/:)',		78 => ':-J',
			79 => '(*)',		100 => ':)]',				101 => ':-C',		102 => '~X(',
			103 => ':-H',		104 => ':-T',				105 => '8->',		24 => '=))',
			107 => '%-(',		108 => ':O3',				1 => array(':)',':-)'),		2 => array(':(',':-('),
			3 => array(';)',';-)'),		22 => array(':|',':-|'),		14 => array('X(','X-('),		15 => array(':>',':->'),
			8 => array(':X',':-X'),		4 => array(':D',':-D'),		27 => '=;',		10 => array(':P',':-P'),
		);
}
	
# Function detail : Replace emoticons to string
# @param <string>	
function replace_emotions($s) {
	$emotions = arr_yahoo_emoticons();
		foreach ($emotions as $a => $b) {
			$x = array();
			if (is_array($b)) {
				for ($i=0;$i<count($b);$i++) {
					$b[$i] = htmlchars($b[$i]);
					$x[] = $b[$i];
					$v = strtolower($b[$i]);
					if ($v != $b[$i]) $x[] = $v;
					//array_push($x,$b[$i],strtolower($b[$i]));
				}
			}
			else {
				$b = htmlchars($b);
				$x[] = $b;
				$v = strtolower($b);
				if ($v != $b) $x[] = $v;
				//$x = array($b,strtolower($b));
			}
			$p = '';
			for ($u=0;$u<strlen($x[0]);$u++) {
				$ord = ord($x[0][$u]);
				if ($ord < 65 && $ord > 90) $p .= '&#'.$ord.';';
				else $p .= $x[0][$u];
			}
				$s = str_replace($x,'<img src=images/emoticons/yahoo/'.$a.'.gif>',$s);
		}
		return $s;
}	

# Function detail : sql injaction anti attack
# @param <string>
function blackrequest_filter($str){
	$str = str_replace("'","",str_replace("\\","",$str));
	$str = str_replace("<?php","",$str);
	$str = str_replace("<?","",$str);
	$str = str_replace("--","",$str);
	$str = str_replace("<script>","",$str);
	$str = preg_replace ("/(<[\s]*script.+?<\\/script>)/mi", "", $str);
	return $str;
}
	
# Function detail : super post method
# @param <string>				
function spost($name) {
	if (isset($_POST[$name])) {
		return blackrequest_filter(trim($_POST[$name]));
	}
	else {
		return "" ;
	}
}

# Function detail : super get method
# @param <string>	
function sget($name) {
	if (isset($_GET[$name])) {
		return blackrequest_filter(trim($_GET[$name]));
	}
	else {
		return "" ;
	}
}
 
# Function detail : get Extension - get file extesion
# @param <string>	
function get_extension($str) {     
	$i = strrpos($str,".");
	if (!$i) {
		return "";
	}
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l); 
	return strtolower($ext);
}
 
# Function detail : array to json encrypt
# @param <string>	 
function array2json($arr) {
	if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
    $parts = array();
    $is_list = false;

    //Find out if the given array is a numerical array
    $keys = array_keys($arr);
    $max_length = count($arr)-1;
    if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
        $is_list = true;
        for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
            if($i != $keys[$i]) { //A key fails at position check.
                $is_list = false; //It is an associative array.
                break;
            }
        }
    }

    foreach($arr as $key=>$value) {
        if(is_array($value)) { //Custom handling for arrays
            if($is_list) $parts[] = array2json($value); /* :RECURSION: */
            else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
        } else {
            $str = '';
            if(!$is_list) $str = '"' . $key . '":';

            //Custom handling for multiple data types
            if(is_numeric($value)) $str .= $value; //Numbers
            elseif($value === false) $str .= 'false'; //The booleans
            elseif($value === true) $str .= 'true';
            else $str .= '"' . addslashes($value) . '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Object?)

            $parts[] = $str;
        }
    }
    $json = implode(',',$parts);
    
    if($is_list) return '[' . $json . ']';//Return numerical JSON
    return '{' . $json . '}';//Return associative JSON
}

 
# Function detail : array to json encrypt
# @param <string>	 
function get_html_source($url,$agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" ){
	if($agent == 2) $agent = "Windows-Media-Player/10.00.00.xxxx";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch,CURLOPT_USERAGENT,$agent); 
		return curl_exec($ch);
}


# Function detail : return nice time
# @param <string>
function get_nice_time($date){
	//return distanceOfTimeInWords($date);
    if(empty($date)) {
        return "Sai định dạng ngày";
    }
    
    $periods         = array("giây", "phút", "giờ", "ngày", "tuần", "tháng", "năm", "quý");
    $lengths         = array("60","60","24","7","4.35","12","10");
    
    $now             = time();
    $unix_date       = strtotime($date);
    
       // check validity of date
    if(empty($unix_date)) {    
        return "Sai kiểu";
    }

    // is it future date or past date
    if($now > $unix_date) {    
        $difference     = $now - $unix_date;
        $tense         = "trước đây";
        
    } else {
        $difference     = $unix_date - $now;
        $tense         = "lúc này";
    }
    
    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }
    
    $difference = round($difference);
    
 /*   if($difference != 1) {
        $periods[$j].= "s";
    }*/
    
    return "$difference $periods[$j] {$tense}";
}


# Function detail : Convert string
# @param <string>	
function cut_str($text, $start=0, $limit=12){
      if (function_exists('mb_substr')){
            $more = (mb_strlen($text) > $limit) ? TRUE : FALSE;
            $text = mb_substr($text, 0, $limit, 'UTF-8');
            return array($text, $more);
      }else if(function_exists('iconv_substr')){
            $more = (iconv_strlen($text) > $limit) ? TRUE : FALSE;
            $text = iconv_substr($text, 0, $limit, 'UTF-8');
            return array($text, $more);
      }else{
            preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);
            if(func_num_args() >= 3){
                  if(count($ar[0])>$limit){
                        $more = TRUE;
                        $text = join("",array_slice($ar[0],0,$limit))."...";
                  }
                  $more = TRUE;
                  $text = join("",array_slice($ar[0],0,$limit));
            }else{
                  $more = FALSE;
                  $text = join("",array_slice($ar[0],0));
            }
            return array($text, $more);
      }
}

# Function detail : Convert string extends cstr
# @param <string>
function news_cut_title($text, $limit=25){
      $val = cut_str($text, 0, $limit);
      return $val[1] ? $val[0]."..." : $val[0];
} 


# Function detail : Return left time
# @param <string>
function distance_of_time($fromTime, $toTime = 0, $showLessThanAMinute = false) {
    $distanceInSeconds = round(abs($toTime - $fromTime));
    $distanceInMinutes = round($distanceInSeconds / 60);
       
        if ( $distanceInMinutes <= 1 ) {
            if ( !$showLessThanAMinute ) {
                return ($distanceInMinutes == 0) ? 'less than a minute' : '1 minute';
            } else {
                if ( $distanceInSeconds < 5 ) {
                    return 'less than 5 seconds';
                }
                if ( $distanceInSeconds < 10 ) {
                    return 'less than 10 seconds';
                }
                if ( $distanceInSeconds < 20 ) {
                    return 'less than 20 seconds';
                }
                if ( $distanceInSeconds < 40 ) {
                    return 'about half a minute';
                }
                if ( $distanceInSeconds < 60 ) {
                    return 'less than a minute';
                }
               
                return '1 minute';
            }
        }
        if ( $distanceInMinutes < 45 ) {
            return $distanceInMinutes . ' minutes';
        }
        if ( $distanceInMinutes < 90 ) {
            return 'about 1 hour';
        }
        if ( $distanceInMinutes < 1440 ) {
            return 'about ' . round(floatval($distanceInMinutes) / 60.0) . ' hours';
        }
        if ( $distanceInMinutes < 2880 ) {
            return '1 day';
        }
        if ( $distanceInMinutes < 43200 ) {
            return 'about ' . round(floatval($distanceInMinutes) / 1440) . ' days';
        }
        if ( $distanceInMinutes < 86400 ) {
            return 'about 1 month';
        }
        if ( $distanceInMinutes < 525600 ) {
            return round(floatval($distanceInMinutes) / 43200) . ' months';
        }
        if ( $distanceInMinutes < 1051199 ) {
            return 'about 1 year';
        }
       
        return 'over ' . round(floatval($distanceInMinutes) / 525600) . ' years';
}


# Function detail : Return left time
# @param <string>
function sql_time(){
	return date("Y-m-d H:i:s");
}

# Function detail : Return left time
# @param <string>
function xmle_value($tagname,$XMLInput) {
	if(preg_match("/<$tagname>(.*?)<\/$tagname>/",$XMLInput,$preg)) 
		return $preg[1];			
	else return "";
}


function replace_block_all($source,$inp = array()){
	foreach($inp as $key => $value ) {
		$source = str_replace('{'.$key.'}',$value,$source);
	}
	return $source;
}



function fviewpage($ttrow, $n, $pg = "", $link){
	if($ttrow < 1) return "";
//	global $link;
	if(!$pg) $pg = 1;
	$link = preg_replace("#&pg=([0-9]{1,})#si","",$link);
	$html ="<ul class='pagedelimiter'>";
	$pgt = $pg-1;
	if ($pg<>1) $html.="<li><a class='pagelink' href='$link"."1' onfocus='this.blur()'  title='Xem trang đầu'>&laquo;&laquo;</li>
	<li><a class='pagelink' href='$link"."$pgt' onfocus='this.blur()' title='Xem trang trước'>&laquo;</li>";
	for($l = 0; $l < $ttrow/$n; $l++) {
		$m = $l+1;
		if($m == $pg) $html .= "<li class='pagecurrent'><a onfocus='this.blur()' class=''>$m</a></li>";
		
		if($m<($pg+3)){
			if($m>=$pg){
				if($m!=$pg){ $html .= "<li><a onfocus='this.blur()' href='$link"."$m' title='Xem trang $m' class='pagelink'>$m</a></li>";
				}else $html .= "<li>...</li>";
			}
		}else break;
	}
	$pgs = $pg+1;
	if ($pg<>$m) $html.="<li><a class='pagelink' href='$link"."$pgs' onfocus='this.blur()' title='Xem trang kế tiếp'>&raquo;</a></li>
	<li><a class='pagelink' href='$link"."$m' onfocus='this.blur()' title='Xem trang cuối'>&raquo;&raquo;</a></li> ";
	
	

	return $html.'</ul>';
}

function sqltime($sql,$format = "d-m-Y"){
	 return date($format,strtotime($sql));
}
	
function acpredirect($url= ''){
	if(!$url)	
		$url = $_SERVER['QUERY_STRING'];
	return "<br><br><center>Đã cập nhật <meta http-equiv='refresh' content='0;url=index.php?".$url."'></center>";
}

function redirect2($url= '')
{
	if($url)
		$url = "?".$url;
		
	return "<meta http-equiv='refresh' content='0;url=index.php".$url."'>";
}
	
?>

 